const jwt = require('jsonwebtoken')
const { secret } = require('../utils/config')
const { promisify } = require('util')
jwtVerify = promisify ( jwt.verify )
module.exports = {
  //操作权限认证（登录后才能增改查）
    requestVerify: async (req, res, next) => {
    //前端所有请求需要验证token
    let token = req.body.token || req.headers['authorization'] || req.cookies.token
    token = token ? token.split('Bearer ')[1] : null
    if (!token) {
      return res.status(401).json({ status: '401', msg: '未登录账号' }).end()
    }
    try {
      await jwtVerify(token, secret)
       next()
    } catch (error) {
      console.log(error.message)
      return res.status(401).json(error.message)
    }
  },

  //页面显示权限（未登录都跳到登录页）
  loginVerify: async (req,res,next)=>{
    let token = req.body.token || req.headers['authorization'] || req.cookies.token
    token = token ? token.split('Bearer ')[1] : null
    if (!token) {
      return res.redirect('/login')
    }
    try {
      await jwtVerify(token, secret)
      next();
    } catch (error) {
      console.log(error.message)
      return res.redirect('/login')
    }
  }
}